package com.luoqiz.demo.ioDemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.junit.Test;

public class IODemo {

	
	@Test
	public void readWithbuffer() throws FileNotFoundException{
		System.out.println("拥有缓冲区字符流读取文件时间测试");
		BufferedReader br=new BufferedReader(new FileReader("d:\\fwtest.txt"));
		char[] c=new char[1024];
		int len=-1;
		int i=0;
		long l=System.currentTimeMillis();
		try {
			while((len=(br.read(c)))!=-1){
				System.out.println("第"+(i++)+"次读取长度："+len);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			System.out.println("耗时："+(System.currentTimeMillis()-l));
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	public void readNobuffer() throws FileNotFoundException{
		System.out.println("无缓冲区字符流读取文件时间测试");
		FileReader fr=new FileReader("d:\\fwtest.txt");
		char[] c=new char[1024];
		int len=-1;
		int i=0;
		long l=System.currentTimeMillis();
		try {
			while((fr.read(c))!=-1){
				System.out.println("第"+(i++)+"次读取长度："+len);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			System.out.println("耗时："+(System.currentTimeMillis()-l));
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	@Test
	public void writeNoBuffer() throws IOException {
		System.out.println("无缓冲区写入时间测试");
		FileWriter fw = new FileWriter("d:\\fwtest.txt");
		long l = System.currentTimeMillis();
		for (int i = 0, n = 1024 * 1024 *3; i < n; i++) {
			fw.write("harr我是一个好人撒rrrrrrrrrrrroohgftertbnbjl;kluj" + i);
		}
		System.out.println("耗时："+(System.currentTimeMillis()-l));
		fw.flush();
		fw.close();
		System.out.println("over");
	}

	@Test
	public void writeWithBuffer() throws IOException {
		System.out.println("有缓冲区写入时间测试");
		BufferedWriter fw = new BufferedWriter(new FileWriter("d:\\aWithbuffer.txt"));
		long l = System.currentTimeMillis();
		for (int i = 0, n = 1024 * 1024 *3; i < n; i++) {
			fw.write("harr我是一个好人撒rrrrrrrrrrrroohgftertbnbjl;kluj" + i);
		}
		System.out.println("耗时："+(System.currentTimeMillis()-l));
		fw.flush();
		fw.close();
		System.out.println("over");
	}
}
